package servlet;

import bean.User;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "IndexServlet", value = "/IndexServlet")
public class IndexServlet extends HttpServlet {

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        // 获取登录记录，看用户是否登录
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();
        // 根据session中的isLogin名字获取登录记录中对象信息
        User user = (User) session.getAttribute("isLogin");
        if (user == null) {
            // 没有用户信息，跳转登录
            String url = "/login_war_exploded/login.html";
            out.println("当前没登录，请登录<a href = '" + url +  "'>登录页面</a>");
        } else {

            String logoutUrl = "/login_war_exploded/logout";
            out.println("欢迎：" + user.getUsername() + "登录     <a href='" + logoutUrl +"'>退出</a>");
            // 有用户信息，则将存有用信息的sessionId发给前端
            Cookie cookie = new Cookie("JSESSIONID", session.getId());
            response.addCookie(cookie);
        }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        this.doGet(request, response);
    }

}

